package com.example.communitypro.util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.apache.catalina.filters.Constants;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    private static final String SING = "abcdefg";

    /**
     * 生成token  header.payload.sing
     */
    public static String getToken(String userNo,String state){
        Calendar istance = Calendar.getInstance();
        istance.add(Calendar.DATE,1);
        return JWT.create()
                .withClaim("userNo",userNo)
                .withClaim("state",state)
                .withExpiresAt(istance.getTime())
                .sign(Algorithm.HMAC256(SING));
    }

    public static String getUserNo(HttpServletRequest request)  {

        String token = request.getHeader("token");
//        System.out.println(token);
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
//        System.out.println(jwt);
        Claim userNo = jwt.getClaim("userNo");
//        System.out.println(userNo);
//        System.out.println(userNo.asString());
        return jwt.getClaim("userNo")
                .asString();

    }

    public static String getUserlevel(HttpServletRequest request)  {

        String token = request.getHeader("token");
//        System.out.println(token);
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
//        System.out.println(jwt);
        Claim userNo = jwt.getClaim("state");
//        System.out.println(userNo);
//        System.out.println(userNo.asString());
        return jwt.getClaim("state")
                .asString();

    }

    /**
     * 验证token 验证合法性  并返回值
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 获取token信息  可以由验证的方法代替（可以不写）
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }

}